package com.ershijin.authserver.handler;

import com.ershijin.authserver.service.security.CustomizerJdbcOAuth2AuthorizationService;
import com.ershijin.common.util.SpringContextHolder;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospection;
import org.springframework.security.oauth2.core.http.converter.OAuth2TokenIntrospectionHttpMessageConverter;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2TokenIntrospectionAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 令牌内省成功后，延长令牌的有效期
 */
public class TokenIntrospectionSuccessHandler implements AuthenticationSuccessHandler {
    private final HttpMessageConverter<OAuth2TokenIntrospection> tokenIntrospectionHttpResponseConverter =
            new OAuth2TokenIntrospectionHttpMessageConverter();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication =
                (OAuth2TokenIntrospectionAuthenticationToken) authentication;
        OAuth2TokenIntrospection tokenClaims = tokenIntrospectionAuthentication.getTokenClaims();
        ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
        this.tokenIntrospectionHttpResponseConverter.write(tokenClaims, null, httpResponse);

        // 延长token的有效期
        if (tokenIntrospectionAuthentication.getTokenClaims().getClaim("active")) {
            SpringContextHolder.getBean(CustomizerJdbcOAuth2AuthorizationService.class).overtime(((OAuth2TokenIntrospectionAuthenticationToken) authentication).getToken());
        }
    }
}
